import * as path from 'path';
import * as fs from 'fs';
import request from "request";
import compressing from "compressing";
import fsx from "@/modules/fs";
// ---- 下载类 ---- //
class StreamDownload {
    constructor() {
        // 声明下载过程回调函数
        this.downloadCallback = null;
    }
    // 下载进度
    showProgress(received, total) {
        const percentage = (received * 100) / total;
        // 用回调显示到界面上
        this.downloadCallback({
            isDownloaded: false,
            filePath: "",
        }, percentage);
    }
    // 下载过程
    downloadFile(patchUrl, downloadPath, installPath, callback) {
        this.downloadCallback = callback; // 注册回调函数
        fsx.mkdirP(downloadPath);
        fsx.mkdirP(installPath);
        let arr = patchUrl.split('/')
        const downloadFile = arr[arr.length - 1]; // 下载文件名称，也可以从外部传进来
        const fileName = downloadFile.split('.')[0];
        let fileDownPath = path.join(downloadPath, downloadFile);
        let fileInstallPath = path.join(installPath, fileName);
        let receivedBytes = 0;
        let totalBytes = 0;
        try {
            let stats = fs.statSync(path);//如果文件已存在读取文件信息
            if (totalBytes == stats.size) {//如果文件已经存在并且已经下载按成则跳过该文件
                return;
            }
            receivedBytes = stats.size;
        } catch (err) {

        }
        const req = request({
            method: 'GET',
            uri: patchUrl
        });
        const out = fs.createWriteStream(fileDownPath);
        req.pipe(out);
        req.on('response', (data) => {
            // 更新总文件字节大小
            totalBytes = parseInt(data.headers['content-length'], 10);
        });
        req.on('data', (chunk) => {
            // 更新下载的文件块字节大小
            receivedBytes += chunk.length;
            this.showProgress(receivedBytes, totalBytes);
        });
        req.on('end', () => {
            compressing.zip
                .uncompress(fileDownPath, fileInstallPath)
                .then(() => {
                    this.downloadCallback({
                        isDownloaded: true,
                        filePath: fileDownPath,
                    }, 100);
                })
                .catch(err => {
                    console.error(err);
                });
            // TODO: 检查文件，部署文件，删除文件

        });
    }
}

export default new StreamDownload()